// src/services/scholarsDashboardService/fetchRecentScholarSearch.ts

import { BASE_URL } from '@/services/apiConfig';

interface RecentScholar {
  student_number: string | null;
  program_id: string | null;
  full_name: string | null;
  email: string | null;
  scholar_type: string | null;
  most_recent_sponsor: string | null;
  most_recent_ite_start: string | null;
  most_recent_ite_end: string | null;
}

interface RecentScholarSearchParams {
  skip?: number;
  limit?: number;
  keywords?: string;
}

interface RecentScholarsResponse {
  total: number;
  scholars: RecentScholar[];
}

const fetchRecentScholarSearch = async (
  params: RecentScholarSearchParams = {}
): Promise<RecentScholarsResponse> => {
  const token = localStorage.getItem('token');
  if (!token) throw new Error('No token found');

  const query = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== '') {
      query.append(key, String(value));
    }
  });

  const res = await fetch(`${BASE_URL}/scholars/dashboard/search?${query.toString()}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Fetch failed: ${res.status} - ${err}`);
  }

  const data = await res.json();
  return data;
};

export { fetchRecentScholarSearch };